// pages/exchange-record/exchange-record.js
Page({
  data: {
    recordList: [],
    totalExchanges: 0,
    totalPoints: 0
  },

  onLoad: function (options) {
    console.log('兑换记录页面加载');
    this.loadExchangeRecords();
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadExchangeRecords();
  },

  // 加载兑换记录
  loadExchangeRecords: function() {
    const records = wx.getStorageSync('exchangeRecords') || [];
    
    // 格式化时间显示
    const formattedRecords = records.map(record => ({
      ...record,
      exchangeTime: this.formatTime(record.exchangeTime)
    }));

    // 计算统计数据
    const totalExchanges = records.length;
    const totalPoints = records.reduce((sum, record) => sum + record.points, 0);

    this.setData({
      recordList: formattedRecords,
      totalExchanges,
      totalPoints
    });
  },

  // 格式化时间
  formatTime: function(timeString) {
    const date = new Date(timeString);
    const now = new Date();
    const diff = now - date;
    
    // 如果是今天
    if (diff < 24 * 60 * 60 * 1000 && date.getDate() === now.getDate()) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
    
    // 如果是昨天
    const yesterday = new Date(now);
    yesterday.setDate(yesterday.getDate() - 1);
    if (date.getDate() === yesterday.getDate() && date.getMonth() === yesterday.getMonth()) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
    
    // 其他时间
    return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  }
});
